package com.ewanghuiju.app.pay;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.ewanghuiju.app.R;
import com.ewanghuiju.app.app.Constants;
import com.ewanghuiju.app.component.RxBus;
import com.ewanghuiju.app.model.event.SendEvent;
import com.muddzdev.styleabletoast.StyleableToast;

import java.util.Map;

public class AliPay {
    Activity activity;

    public AliPay(Activity activity) {
        this.activity = activity;
    }

    public void pay(final String orderInfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = 0;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String resultStatus = "";
            Map<String, String> result = (Map) msg.obj;
//            LogUtil.e(JSON.toJSONString(result));
            for (Map.Entry entry : result.entrySet()) {
                String key = (String) entry.getKey();
                String value = (String) entry.getValue();
                if (key.equals("resultStatus")) {
                    resultStatus = value;
                }

            }
            if (resultStatus.equals("9000")) {
                RxBus.getDefault().post(new SendEvent("", Constants.TYPE_PAY_STATUS_RETURN, new PayReslut(PayReslut.ALIPAY, 0)));
            } else {
                RxBus.getDefault().post(new SendEvent("", Constants.TYPE_PAY_STATUS_RETURN, new PayReslut(PayReslut.ALIPAY, -1)));
            }
        }
    };
}
